package com.six.interceptor;

import com.alibaba.fastjson.JSON;
import com.six.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//拦截器 Springmvc
//浏览器-----前端控制器-----处理器映射器
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //用户登录，系统会给浏览器发送一个token
        //浏览器受到这个token，需要记录下去
        //之后浏览器每次发送请求需要携带这个token  将token放到header中，如果有token就是登陆过的
        //在拦截器中拦截每一个请求，获取header中的token，如果获取到就放行，没货的就截止
        String token=request.getHeader("authentication");
        if(token==null||token.isEmpty()){
            Result result=Result.fail(401,"认证失败");
            //转化为json格式
            String json = JSON.toJSONString(result);
            response.getWriter().write(json);
            return false;

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
